<!--
 * @Description: 
 * @version: 
 * @Author: liurui
 * @Date: 2024-02-01 13:39:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-02-04 14:16:01
-->
<template>
    <div>
        <h1>我的宠物，{{ pet }}</h1>
    </div>
</template>

<script setup lang="ts">
/**
 * 在此挑战中，我们想通过在联合类型Cat | Dog中搜索公共type字段来获取相应的类型。
 * 换句话说，在以下示例中，我们期望LookUp<Dog | Cat, 'dog'>获得Dog，LookUp<Dog | Cat, 'cat'>获得Cat
 */

 interface Cat {
  type: 'cat';
  breeds: 'Abyssinian' | 'Shorthair' | 'Curl' | 'Bengal';
}

interface Dog {
  type: 'dog';
  breeds: 'Hound' | 'Brittany' | 'Bulldog' | 'Boxer';
  color: 'brown' | 'white' | 'black';
}

//  T 是联合类型，触发TS分发特性
// Cat | Dog extends { type: T }  等同于 Cat extends {type: T} | Dog extends {type: T}
type LookUp<T, U> = T extends { type: U } ? T : never;

type MyDog = LookUp<Cat | Dog, 'dog'>; // expected to be `Dog`

// 场景案例：我打算从猫和狗中选择一个作为宠物，我选择了猫

type Animal = Cat | Dog;

const aPet: Cat = {type: 'cat', breeds: 'Abyssinian'};

type myPet = LookUp<Animal, 'cat'>; // 

let pet: myPet = aPet;

</script>

<style scoped>

</style>